package com.bilibili.service.impl;

import com.bilibili.entity.PicCartoon;
import com.bilibili.entity.PicPage;
import com.bilibili.entity.PicRead;
import com.bilibili.exception.BusinessException;
import com.bilibili.mapper.PicCartoonMapper;
import com.bilibili.mapper.PicPageMapper;
import com.bilibili.mapper.PicReadMapper;
import com.bilibili.service.PicReadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Service
public class PicReadServiceImpl implements PicReadService {

    @Autowired
    private PicReadMapper picReadMapper;

    @Autowired
    private PicCartoonMapper picCartoonMapper;

    @Autowired
    private PicPageMapper picPageMapper;

    @Override
    public List<PicRead> getPicReadByPageId(Integer pageId) {
        List<PicRead> picReads = picReadMapper.getPicReadByPageId(pageId);
        if (picReads.size()==0){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "章节id不存在");
        }
        //以number将每一话排序
        picReads.sort(Comparator.comparingInt(PicRead::getOrder));
        return picReads;
    }

    @Override
    public List<PicRead> getPagesByNumberAndCartoonId(Integer number, Integer cartoonId, Integer action) {
        PicCartoon cartoonById = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoonById)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画id不存在");
        }
        PicPage picPage = picPageMapper.getPagesByNumberAndCartoonId(number, cartoonId);
        if (Objects.isNull(picPage)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "所个参数漫画id与章节数对应的实体类不存在");
        }
        PicPage pageForAction = picPageMapper.getPagesByNumberAndCartoonId(number + action, cartoonId);
        if (Objects.isNull(pageForAction)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "请求的章节不存在");
        }
        Integer pageId = pageForAction.getId();
        List<PicRead> picReads = picReadMapper.getPicReadByPageId(pageId);
        if (Objects.isNull(picReads)||picReads.size()==0){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "请求的章节具体的漫画还没有上传");
        }
        //以number将每一话排序
        picReads.sort(Comparator.comparingInt(PicRead::getOrder));
        return  picReads;
    }

}
